package com.khson.knows.portal.security;

import com.khson.knows.portal.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
//启动SpringSecurity
//@EGMS, =true,表示开启权限管理功能
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //编写一个方法,java代码中设置用户名密码实心登录
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在用户点击登录时,会出发这个方法,这个方法会调用我们编写的
        //loadUserbyUsername方法,根据与用户输入的用户名查询用户详情
        //至于登录是否成功,以及验证登录过程,都在框架中封装了,我们只能在页面上看到结果
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()//对请求进行授权设置
            .antMatchers(//设置匹配路径
                    "/js/*"
                    ,"/css/*"
                    ,"/img/**"
                    ,"/bower_components/**"
                    ,"/login.html"
                    ,"/register.html"
                    ,"/register"
            ).permitAll()   //表示上述路劲全部允许直接访问
            .anyRequest().authenticated()   //其他请求需要登录之后才能访问
            .and().formLogin() //登录使用表单认证
            .loginPage("/login.html")   //设置自定义登录页面路径
            .loginProcessingUrl("/login")   //设置处理登录的路径,"/login"是页面表单提交的路径
            .failureUrl("/login.html?error")    //设置登录失败的路径."?error"框架内置,显示登录失败的信息
            .defaultSuccessUrl("/index_student.html")   //设置登录成功的页面
            .and().logout() //设置登出
            .logoutUrl("/logout")   //设置登出路径
            .logoutSuccessUrl("/login.html?logout")    //设置登出页面,显示登出成功
            .and().csrf().disable();    //关闭防跨域攻击,不关闭无法登录

    }
}
